package com.spike.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spike.common.R;
import com.spike.model.User;
import com.spike.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
@AllArgsConstructor
public class UsersController {
    private UserService userService;

    @PostMapping("register")
    public R register(@RequestBody User user) {
        Integer userId = userService.register(user);
        if (userId == -1) {
            return new R(400,"该手机号已被注册",null);
        }else
        {
            Map<String, Integer> map = new HashMap<>();
            map.put("user_id",userId);
            return new R(200,"注册成功",map);
        }
    }
    @PostMapping("login")
    public R login(@RequestBody User user) {
         Boolean bool = userService.login(user);
        Map<String, String> map = new HashMap<>();
        map.put("token","会话令牌");
         if (bool) {
             return new R(200,"登录成功",map);
         }else
             return new R(400,"登录失败",null);
    }
    @PutMapping("{user_id}")
    public R updateUser(@PathVariable("user_id") Integer userId, @RequestBody User user) {
        Boolean update = userService.update(userId,user);
        if (update) {
            return new R(200,"更新成功",null);
        }else
            return new R(409,"版本冲突，请刷新数据",null);
    }
    @PostMapping("{user_Id}/delete")
    public R deleteUser(@PathVariable("user_Id") Integer userId,@RequestBody User user) {
        Boolean delete = userService.delete(userId,user.getVersion());
        if (delete) {
            return new R(200,"删除成功",null);
        }else
            return new R(409,"版本冲突，请刷新数据",null);
    }
}
